<template>
  <div class="user">
      <div class="useradd">
        <el-button type="primary" @click="addUserBtn">+ 新增用户</el-button>
      </div>
      <div class="user-search">
        <ul>
          <li><span>登录名</span>
            <el-input v-model="searchQuery.account" placeholder="请输入登录名"></el-input>
          </li>
          <li><span>所属部门</span>
            <el-input v-model="searchQuery.orgName" placeholder="请输入所属部门"></el-input>
          </li>
        </ul>
        <el-button type="primary" @click="searchQueryFn">查询</el-button>
      </div>
      <div class="user-table">
        <el-table :data="userData" style="width: 100%" border stripe v-loading="loading">
          <el-table-column prop="userName" label="用户姓名">
          </el-table-column>
          <el-table-column prop="account" label="登录名">
          </el-table-column>
          <el-table-column prop="orgName" label="所属部门">
          </el-table-column>
          <el-table-column prop="leader" label="是否部门领导" width="150px">
            <template slot-scope="scope">
              <span v-if="scope.row.leader == true">是</span>
              <span v-if="scope.row.leader == false">否</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="status" label="所属角色">
          </el-table-column> -->
          <el-table-column prop="" label="操作" width="180px">
              <template slot-scope="scope">
                  <el-button type="text" @click="editUserFn(scope)">编辑</el-button>
                  <el-button type="text" @click="delUserFn(scope)">删除</el-button>
                  <el-button type="text" @click="resetPassWordFn(scope)">重置密码</el-button>
              </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParam.currPage"
          :page-sizes="[20, 30, 50, 100]"
          :page-size="pageParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageParam.totalSize">
        </el-pagination>
      </div>
      <!-- 新增用户 -->
      <el-dialog :visible.sync="dialogFormVisible" v-if="isShow" :before-close="handleClose">
        <el-form :model="userForm" :rules="rules" ref="userForm" label-width="140px" label-position="right">
          <el-form-item label="用户姓名" prop="userName">
            <el-input v-model="userForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="id" prop="userId" v-if="false">
            <el-input v-model="userForm.userId"></el-input>
          </el-form-item>
          <el-form-item label="登录名" prop="account">
            <el-input v-model="userForm.account"></el-input>
          </el-form-item>
          <el-form-item label="所属部门leader" prop="isLeader">
            <el-select v-model="userForm.isLeader" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.label"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请选择所属部门" prop="orgName">
            <el-input v-model="userForm.orgName" :disabled="true"></el-input>
            <el-tree
              show-checkbox
              check-strictly
              node-key="id"
              ref="tree"
              lazy
              :load="loadNode"
              highlight-current
              @check-change="handleCheckChange"
              :props="propsTree">
            </el-tree>
          </el-form-item>
          <el-form-item label="请选择角色" prop="role">
            <el-input v-model="userForm.role" :disabled="true"></el-input>
            <el-tree
              :data="rolelist"
              show-checkbox
              node-key="id"
              ref="treeRole"
              @check-change="roleCheckChange"
              :props="defaultProps">
            </el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUserSure('userForm')">确 定</el-button>
          <el-button @click="cancleForm('userForm')">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 是否重置 -->
      <el-dialog
        :visible.sync="dialogVisible"
        width="30%">
        <span> {{resetMsg}} </span>
      </el-dialog>
  </div>
</template>

<script>

  import {getOrgQuery, userQuery, resetPassWord, addUser, userMsg, editUser, delUser} from '@/server/userManagement'
  import Api from "@/server/tree"

  export default {
    data: () => ({
      loading: true,
      searchQuery:{
        account: '',
        orgName: '',
        currPage: 0,
        pageSize: 30
      },
      pageParam:{
        currPage: 1,
        totalSize: 0,
        pageSize: 30
      },
      resetMsg:'',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      propsTree: {
        label: 'orgName',
        children: 'children',
        isLeaf: 'leaf'
      },
      orgNamelist:[],
      rolelist:[
        {
          id: '1',
          label: '业务员'
        },
        {
          id: '2',
          label: '业务领导'
        },
        {
          id: '3',
          label: '单证员'
        },
        {
          id: '4',
          label: '单证领导'
        },
        {
          id: '5',
          label: '风控员'
        },
        {
          id: '6',
          label: '财务'
        },
        {
          id: '7',
          label: '管理员'
        }
      ],
      userData: [],
      dialogVisible: false,
      isEditUser: false,
      isShow: false,
      dialogFormVisible: false,
      userForm: {
          userName: '',
          account: '',
          isLeader: '',
          orgId: '',
          orgName: '',
          role: '',
          roleId: ''
      },
      options: [
        {
          value: 'true',
          label: '是'
        }, {
          value: 'false',
          label: '否'
        }
      ],
      //新增用户表单校验规则
      rules: {
        userName: [
            { required: true, message: '请输入用户姓名', trigger: 'blur' },
        ],
        account: [
            { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        isLeader: [
            { required: true, message: '请选择所属部门leader', trigger: 'change' }
        ],
        orgName: [
            { required: true, message: '请选择一个部门', trigger: 'change' }
        ],
        role: [
            { required: true, message: '请至少选择一个角色', trigger: 'change' }
        ]
      },
    }),
    // props: ['userData'],
    mounted() {
      this.initPage();
      this.getUserQueryFn();
    },
    // async mounted() {
    //   //一级树
    //   let getRootBus = await Api.getRootBus()
    //   this.orgNamelist = getRootBus
    //   console.log(getRootBus,'----getRootBus');
    // },
    methods: {
      initPage() {
        this.searchQuery.currPage = 0;
        this.searchQuery.pageSize = 30;
      },
      //新增用户
      addUserFn(paramObj) {
        addUser(paramObj).then((res) => {
          try {
            if (res.code) {
             this.$message({
                showClose: true,
                message: res.message,
                type: 'success'
              });
             this.getUserQueryFn();
            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('新增用户失败');
          }

        })
      },
      //编辑用户
      editUserFn(val) {

        this.dialogFormVisible = true;

        this.isEditUser = true;

        this.initUserForm();

        let userVal = val.row;
        this.userForm.userId = userVal.id;
        this.userForm.userName = userVal.userName;
        this.userForm.account = userVal.account;
        this.userForm.isLeader = !userVal.leader ? '否' : '是';
        this.userForm.orgId = userVal.orgId;
        this.userForm.orgName = userVal.orgName;
        // this.userForm.role = !userVal.role ? '' : userVal.role;
        // this.userForm.roleId = !userVal.roleId ? '' : userVal.roleId;

        userMsg({userId: userVal.id}).then((res) => {

            if (res.code) {
              let sData = res.data.datas,
                  aRole = [],aRoleId = [];

              sData.forEach((value,index) => {

                aRole.push(value.roleName);
                aRoleId.push(value.roleId);
              });

              this.userForm.role = aRole.toString();
              this.userForm.roleId = aRoleId.toString();
              this.$refs.treeRole.setCheckedKeys(aRoleId);

            } else {
             this.$message.error(res.message);
            }

        })

      },
      //编辑用户-保存
      editUserSaveFn(paramObj) {
        if (paramObj.isLeader === '是') {
          this.userForm.isLeader = true;
        }else if (paramObj.isLeader === '否') {
          this.userForm.isLeader = false;
        }
        editUser(paramObj).then((res) => {
          try {
            if (res.code) {
             this.$message({
                showClose: true,
                message: res.message,
                type: 'success'
              });
             this.getUserQueryFn();
            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('修改用户失败');
          }

        })
      },
      //初始化form
      initUserForm() {

          this.isShow = true;
          this.userForm.userId = '';
          this.userForm.userName = '';
          this.userForm.account = '';
          this.userForm.isLeader = '';
          this.userForm.orgId = '';
          this.userForm.orgName = '';
          this.userForm.role = '';
          this.userForm.roleId = '';
      },

      //查询列表
      searchQueryFn(){
        if (!this.searchQuery.orgName) delete this.searchQuery.orgName;
        if (!this.searchQuery.account) delete this.searchQuery.account;
        this.initPage();
        this.getUserQueryFn(this.searchQuery)
      },
      //每页 ${val} 条
      handleSizeChange(val) {
        this.searchQuery.currPage = 0;
        this.searchQuery.pageSize = `${val}`;
        this.getUserQueryFn(this.searchQuery)
      },
      //当前页: ${val}
      handleCurrentChange(val) {
        this.searchQuery.currPage = `${val}` - 1;
        this.getUserQueryFn(this.searchQuery)
      },
      //用户列表
      getUserQueryFn(paramObj) {
        this.loading = true;
        userQuery(paramObj).then((res) => {

          if (res.code == '1') {
           let sData = res.data.datas;
           this.userData = sData;
           this.pageParam.pageSize = res.data.pageSize;
           this.pageParam.currPage = res.data.currPage + 1;
           this.pageParam.totalSize = res.data.totalSize;
          } else {
           this.$message.error(res.message);
          }

          this.loading = false;

        })
      },
      //删除当前用户
      delUserFn(val) {

        let curRow = val.row;

        this.$confirm('确认删除当前用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          delUser({userId: curRow.id}).then((res) => {
            if (res.code) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });

            } else {
              this.$message(res.message);
            }
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });

      },
      //重置密码
      resetPassWordFn (val) {

        let curRow = val.row;

        resetPassWord({userId: curRow.id}).then((res) => {

          if (res.code) {
            try {
              let sData = res.data.datas[0];
              this.dialogVisible = true

              this.resetMsg = `${curRow.account}重置密码为：${sData}`
            } catch (e) {
              this.$message('重置密码失败');
            }

          } else {
            this.$message(res.message);
          }
        })

      },
      //获取一级树
      async getRootNode() {
        let getRootBus = await Api.getRootBus()
        this.orgNamelist = getRootBus
      },
      //按需加载tree
      async loadNode(node, resolve, reject) {

        let nD = node.data;
        // if (node.data.pid === -1) {
          // return resolve([{ orgName: '公司',id: 1,pid: -1 }]);
        // }
        let subBus = [];

        subBus = await Api.getSubBus({
          pid: nD ? nD.id : -1 ,
          status: 1
        });
        resolve(subBus);

      },
      //获取用户列表
      getOrgQueryFn(paramObj) {

        getOrgQuery(paramObj).then((res) => {

          if (res.code == '1') {
           let sData = res.data.datas;
           this.userData = sData;
          } else {
           this.$message.error(res.message);
          }

        })
      },
      //选择部门
      handleCheckChange(data, checked, indeterminate) {
        var _this = this;
        if(new Date().getTime() - _this.timeStr < 300 ) {
          return
        } else {
          _this.timeStr = new Date().getTime();
        }
        // console.log(data, checked, indeterminate);
        let curkey = data.id;
        if (checked) {
          this.$refs.tree.setCheckedKeys([curkey]);
          this.userForm.orgName = data.orgName;
          this.userForm.orgId = parseInt(curkey);
        }else{
          this.$refs.tree.setCheckedKeys([]);
          this.userForm.orgName = '';
          this.userForm.orgId = '';

        }

      },
      //选择角色
      roleCheckChange(data, checked, indeterminate) {
        this.userForm.role = '';

        let curArrLabel = '',
            curArrId = this.$refs.treeRole.getCheckedKeys(),
            curArr = this.$refs.treeRole.getCheckedNodes();

        for (var value of curArr) {
          curArrLabel += value.label + '，';
        }
        this.userForm.role = curArrLabel.slice(-1) == '，'  ? curArrLabel.slice(0, -1) : curArrLabel;
        this.userForm.roleId = curArrId.toString();

      },
      //重置tree勾选项
      resetChecked() {
        try {
          this.$refs.tree.setCheckedKeys([]);
          this.$refs.treeRole.setCheckedKeys([]);
        } catch (e) {}

      },
      resetForm(formName) {
        this.initUserForm();
        this.$refs[formName].resetFields();
      },
      //新增用户确认
      addUserSure (formName) {

        this.$refs[formName].validate((valid) => {
         if (valid) {
           this.dialogFormVisible = false;
           this.isShow = false;
          //  delete this.userForm.orgName;
          //  delete this.userForm.role;

          (this.isEditUser) ? this.editUserSaveFn(this.userForm) : this.addUserFn(this.userForm);

         } else {
          //  console.log('error submit!!');
           return false;
         }
        });
      },
      addUserBtn(){

        // this.getRootNode();
        // this.resetForm('userForm');
        // this.$refs[formName].resetFields();
        this.dialogFormVisible = true;

        this.isEditUser = false;

        this.initUserForm();

      },
      handleClose() {
        // this.$refs[formName].resetFields();
        this.dialogFormVisible = false;
        this.isShow = false;
      },
      cancleForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogFormVisible = false;
        this.isShow = false;
      }
    }
  }
</script>

<style lang="sass">
  @import "../../../assets/css/common.sass"
  .user-search
    margin-top: 20px
    width: 100%
    border: 1px solid #e6ebf5
    border-radius: 4px
    padding: 20px
    padding-bottom: 10px
    box-sizing: border-box
    &:after
      @include clear
    ul
      width: 90%
      float: left
      &:after
        @include clear
      li
        width: 33%
        height: 40px
        line-height: 40px
        float: left
        padding-right: 10px
        box-sizing: border-box
        margin-bottom: 10px
        span
          font-size: 14px
          display: inline-block
          // width: 30%
          margin-right: 10px
        .el-input, .el-select,
          width: 60%
        .block
          width: 60%
          display: inline-block
          div
            width: 100%
            border: 1px solid #d8dce5
    .el-button
      width: 10%
      height: 40px
  .user-table
    // box-sizing: border-box
    // border: 1px solid #e6ebf5
    // border-radius: 4px
    margin-top: 20px
    // border-right: none
    .el-table
      border-radius: 4px
      .el-table__body-wrapper
        overflow: hidden
  .el-form-item
    margin-bottom: 20px
    .el-input, .el-textarea, .upload-demo
      width: 95%
  .el-dialog__body
    padding-left: 30px
    .el-input~.el-tree
      margin-top: 10px

</style>
